package com.liukai.bishe.presenter.loginAndRegisterPresenter.impl;

import com.alibaba.fastjson.JSON;
import com.liukai.bishe.model.API;
import com.liukai.bishe.model.doman.user.User;
import com.liukai.bishe.model.doman.user.UserMessage;
import com.liukai.bishe.presenter.loginAndRegisterPresenter.IRegisterPresenter;
import com.liukai.bishe.utils.RetrofitManager;
import com.liukai.bishe.utils.ToastUtil;
import com.liukai.bishe.view.IBaseCallBack;
import com.liukai.bishe.view.IRegisterCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class RegisterPresenterImpl implements IRegisterPresenter {

    private IRegisterCallBack mIRegisterCallBack = null;
    private Retrofit mRetrofit;


    /**
     * 发起注册网络请求
     * @param user
     */
    @Override
    public void register(User user) {
        ToastUtil.log("onResponse","注册","注册");
        String userString = JSON.toJSONString(user);

        mRetrofit = RetrofitManager.getInstance().getRetrofit();
        API api = mRetrofit.create(API.class);
        Call<UserMessage> registerTask = api.register(userString);
        registerTask.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    UserMessage userMessage = response.body();
                    ToastUtil.log("onResponse","注册成功",userMessage.toString());
                    // 请求成功,将数据返回给Activity
                    mIRegisterCallBack.result(userMessage);
                }
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                ToastUtil.log("onFailure","注册失败",t.toString());
            }
        });

    }

    @Override
    public void registerCallback(IBaseCallBack iBaseCallBack) {

        mIRegisterCallBack = (IRegisterCallBack) iBaseCallBack;

    }

    @Override
    public void unregisterCallback(IBaseCallBack iBaseCallBack) {

        mIRegisterCallBack = null;

    }


}
